# -*- coding:utf-8 -*-

import cv2
import numpy as np
import time
import os




def split_picture(img_filepath):
    # 以灰度模式读取图片
    gray = cv2.imread(img_filepath, 0)
    # 将图片的边缘变为白色
    height, width = gray.shape
    for i in range(width):
        gray[0, i] = 255
        gray[height-1, i] = 255
    for j in range(height):
        gray[j, 0] = 255
        gray[j, width-1] = 255
    # 中值滤波
    blur = cv2.medianBlur(gray, 3) #模板大小3*3
    #print(blur)
    # 二值化
    ret, thresh1 = cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY)
    #print(thresh1)
    cv2.imwrite('./char/aa.png', thresh1)
    contours, hierarchy = cv2.findContours(thresh1, 2, 2)
    flag = 1
    for cnt in contours:
        # 最小的外接矩形
        x, y, w, h = cv2.boundingRect(cnt)
        if x != 0 and y != 0 and w*h >= 100:
            print((x,y,w,h))
            # 显示图片
            cv2.imwrite("./char/" + '%s.jpg'%flag, thresh1[y:y+h, x:x+w])
            flag += 1

def remove_edge_picture(imagepath):

    image = cv2.imread(imagepath, 0)
    height, width = image.shape
    corner_list = [image[0,0] < 127,
                   image[height-1, 0] < 127,
                   image[0, width-1]<127,
                   image[ height-1, width-1] < 127
                   ]
    if sum(corner_list) >= 3:
        os.remove(imagepath)
import uuid
def resplit_with_parts(imagepath, parts):
    image = cv2.imread(imagepath, 0)
    height, width = image.shape

    # 将图片重新分裂成parts部分
    step = width//parts     # 步长
    start = 0             # 起始位置
    for _ in range(parts):
        cv2.imwrite("./char/" + "%s.jpg"%uuid.uuid1(), image[:, start:start+step])
        start += step

    os.remove(imagepath)

def resplit(imagepath):

    image = cv2.imread(imagepath, 0)
    height, width = image.shape

    if width >= 64:
        resplit_with_parts(imagepath, 4)
    elif width >= 48:
        resplit_with_parts(imagepath, 3)
    elif width >= 26:
        resplit_with_parts(imagepath, 2)



split_picture("./img/t1.jpg")

dir = './char'
for file in os.listdir(dir):
    remove_edge_picture(imagepath=dir+'/'+file)
for file in os.listdir(dir):
    resplit(imagepath=dir+'/'+file)






img_filepath = './img/1.jpg'
# 载入图片
im = cv2.imread(img_filepath)
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
# 将图片做二值化处理
ret, im_inv = cv2.threshold(im_gray,127,255,cv2.THRESH_BINARY_INV)
# 高斯模糊对图片进行降噪
kernel = 1 / 16 * np.array([[1,2,1], [2,4,2], [1,2,1]])
im_blur = cv2.filter2D(im_inv, -1, kernel)
# 二值化处理
ret, im_res = cv2.threshold(im_blur,127,255,cv2.THRESH_BINARY)
# cv2.imshow("Image-New", im_res)
cv2.imwrite('./char/aa.png', im_res)
# 切割图片
contours, hierarchy = cv2.findContours(im_res, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)


w_max =50
result = []
for contour in contours:
    x, y, w, h = cv2.boundingRect(contour)
    if w == w_max: # w_max是所有contonur的宽度中最宽的值
        box_left = np.int0([[x,y], [x+w/2,y], [x+w/2,y+h], [x,y+h]])
        box_right = np.int0([[x+w/2,y], [x+w,y], [x+w,y+h], [x+w/2,y+h]])
        result.append(box_left)
        result.append(box_right)
    else:
        box = np.int0([[x,y], [x+w,y], [x+w,y+h], [x,y+h]])
        result.append(box)

for box in result:
    cv2.drawContours(im, [box], 0, (0,0,255),2)
    roi = im_res[box[0][1]:box[3][1], box[0][0]:box[1][0]]
    roistd = cv2.resize(roi, (50, 50)) # 将字符图片统一调整为30x30的图片大小
    timestamp = int(time.time() * 1e6) # 为防止文件重名，使用时间戳命名文件名
    filename = "{}.jpg".format(timestamp)
    filepath = os.path.join("./char", filename)
    cv2.imwrite(filepath, roistd)